package com.liuyongsheng.teafile.controller;

import com.liuyongsheng.teafile.service.PdfConversionService;
import com.liuyongsheng.teafile.util.FileStorageUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.http.MediaType;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 文件上传控制器
 */
@RestController
@RequestMapping("/api/files")
public class FileUploadController {

    @Autowired
    private FileStorageUtil fileStorageUtil;

    @Autowired
    private PdfConversionService pdfConversionService;

    /**
     * 文件删除接口
     * @param fileUrls 要删除的文件URL数组
     * @return 删除结果
     */
    @PostMapping("/delete")
    public ResponseEntity<?> deleteFiles(@RequestParam("fileUrls") List<String> fileUrls) {
        Map<String, Boolean> deleteResults = fileStorageUtil.deleteFiles(fileUrls);
        return ResponseEntity.ok(deleteResults);
    }

    /**
     * 文件上传接口
     * @param file 上传的文件
     * @return 包含文件URL的响应
     */
    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<?> uploadFile(
        @RequestParam("file") MultipartFile file) {
        try {
            // 存储原始文件
            String storedFilePath = fileStorageUtil.storeFile(file.getBytes(), file.getOriginalFilename());
            String fileUrl = fileStorageUtil.getFileUrl(storedFilePath);

            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("originalFileUrl", fileUrl);

            // 如果是PDF文件，进行转换
            if (file.getContentType() != null && file.getContentType().equals("application/pdf")) {
                // 使用存储后的文件路径生成PDF URL
                String pdfUrl = fileStorageUtil.getPdfUrl(storedFilePath);
                result.put("originalFileUrl", pdfUrl);

                List<String> imageUrls = pdfConversionService.convertPdfToImages(file.getBytes(), file.getOriginalFilename());
                result.put("convertedImageUrls", imageUrls);
            }

            return ResponseEntity.ok(result);
        } catch (IOException e) {
            return ResponseEntity.internalServerError().body("文件处理失败：" + e.getMessage());
        }
    }
}
